
const DEBUG = true

function TmrStoreInt64(key, val) {
  return hmFS.SysProSetInt64(key, val)
}

function TmrLoadInt64(val) {
  return hmFS.SysProGetInt64(val)
}

function TmrLoadInt64ByDefault(key, default_) {
  if (!_check_undefined(res = hmFS.SysProGetInt64(key))) {
    return res
  }
  return default_
}

function TmrStoreInt(key, val) {
  return hmFS.SysProSetInt(key, val)
}

function TmrLoadInt(val) {
  return hmFS.SysProGetInt(val)
}

function TmrLoadIntByDefault(key, default_) {
  if (!_check_undefined(res = hmFS.SysProGetInt(key))) {
    return res
  }
  return default_
}

function TmrGetMinAndSec(target_sec) {
  let cur_sec = _get_time_sec()
  let delta = target_sec - cur_sec

  if (delta < 0) {
    return [-1, -1]
  }

  let sec = delta % 60
  let min = Math.floor(delta / 60)

  return [min, sec]
}

function TmrTimeDeltaToMinAndSec(delta) {
  if (delta < 0) {
    return [-1, -1]
  }

  let sec = delta % 60
  let min = Math.floor(delta / 60)

  return [min, sec]
}

function Panic(err_msg) {
  console.log('Timer Panic: ' + err_msg)
  hmApp.reloadPage({ url: 'page/error', param: err_msg })
}

function _check_undefined(obj) {
  return typeof(obj) == 'undefined'
}

function _get_time_sec() {
  return Math.floor(hmSensor.createSensor(hmSensor.id.TIME).utc / 1000)
}

const KEY_START_TIME_I64 = '__TIMER_START_TIME__'
const KEY_TIMER_STATE_I32 = '__TIMER_STATE__'
const KEY_TIME_TARGET_SEC_I64 = '__TIMER_TARGET_SECOND__'
const KEY_ALARM_ID_I32 = '__TIMER_ALARM_IDX__'

/*
 * timer state:
 * 0: init
 * 1: running
 * 2: paused
 * 3: finish
 */


Page({
  _build_init_page() {
    let user_sec = 0
    let user_min = 0
    //记录点击位置
    let tempCount = 0;

    console.log('_build_init_page() called')

    let alarm_id = TmrLoadInt(KEY_ALARM_ID_I32)
    if (!_check_undefined(alarm_id)) {
      hmApp.alarmCancel(alarm_id)
    }

    hmUI.createWidget(hmUI.widget.TEXT, {
      x: 0,
      y: 50,
      w: 192,
      h: 20,
      color: 0xffffff,
      text_size: 20,
      align_h: hmUI.align.CENTER_H,
      align_v: hmUI.align.CENTER_V,
      text_style: hmUI.text_style.NONE,
      text: '倒计时'
    })

    const min_text = hmUI.createWidget(hmUI.widget.TEXT, {
      x: 10,
      y: 180,
      w: 86,
      h: 50,
      color: 0xffffff,
      text_size: 50,
      align_h: hmUI.align.CENTER_H,
      align_v: hmUI.align.CENTER_V,
      text_style: hmUI.text_style.NONE,
      text: '00'
    })

    const sec_text = hmUI.createWidget(hmUI.widget.TEXT, {
      x: 106,
      y: 180,
      w: 86,
      h: 50,
      color: 0xffffff,
      text_size: 50,
      align_h: hmUI.align.CENTER_H,
      align_v: hmUI.align.CENTER_V,
      text_style: hmUI.text_style.NONE,
      text: '00'
    })

    let set_sec_func = (sec_delta) => {
      if (user_sec + sec_delta > 59) {
        user_sec = 0
      } else if (user_sec + sec_delta < 0) {
        user_sec = 59
      } else {
        user_sec += sec_delta
      }

      sec_text.setProperty(
        hmUI.prop.TEXT, String(Math.floor(user_sec)).padStart(2, '0'))
    }

    let set_min_func = (min_delta) => {
      if (user_min + min_delta > 99) {
        user_min = 0
      } else if (user_min + min_delta < 0) {
        user_min = 99
      } else {
        user_min += min_delta
      }

      min_text.setProperty(
        hmUI.prop.TEXT, String(Math.floor(user_min)).padStart(2, '0'))
    }

    //分钟滑动
    const minGroup = hmUI.createWidget(hmUI.widget.GROUP, {
      x:10,
      y:110,
      w:86,
      h:190
    })

    minGroup.addEventListener(hmUI.event.MOVE,(info)=>{
      if (tempCount == 0) {
        tempCount=info.y;
        return;
      }
      if (tempCount > info.y) {
        console.log("向上滑动{}",tempCount-info.y);
        set_min_func(1)
      } else if (tempCount < info.y){
        console.log("向下滑动",info.y-tempCount);
        set_min_func(-1)
      }
      tempCount=info.y;
      console.log("{}y",info.y)
    })

    minGroup.addEventListener(hmUI.event.CLICK_DOWN,()=>{
      tempCount = 0
      console.log("重置",tempCount)
    })

    //秒滑动
    const secGroup = hmUI.createWidget(hmUI.widget.GROUP,{
      x:106,
      y:110,
      w:86,
      h:190
    })

    secGroup.addEventListener(hmUI.event.MOVE,(info)=>{
      if (tempCount == 0) {
        tempCount=info.y;
        return;
      }
      if (tempCount > info.y) {
        console.log("向上滑动{}",tempCount-info.y);
        set_sec_func(1)
      } else if (tempCount < info.y){
        console.log("向下滑动",info.y-tempCount);
        set_sec_func(-1)
      }
      tempCount=info.y;
      console.log("{}y",info.y)
    })

    secGroup.addEventListener(hmUI.event.CLICK_DOWN,()=>{
      tempCount = 0
      console.log("重置",tempCount)
    })

    const min_up_button = minGroup.createWidget(hmUI.widget.BUTTON, {
      x: 0,
      y: 0,
      text: '',
      w: 86,
      h: 50,
      normal_src: 'up_btn.png',
      press_src: 'up_btn_active.png',
      click_func: () => {
        set_min_func(1)
      }
    })

    const sec_up_button =secGroup.createWidget(hmUI.widget.BUTTON, {
      x: 0,
      y: 0,
      text: '',
      w: 86,
      h: 50,
      normal_src: 'up_btn.png',
      press_src: 'up_btn_active.png',
      click_func: () => {
        set_sec_func(1)
      }
    })

    const min_down_button = minGroup.createWidget(hmUI.widget.BUTTON, {
      x: 0,
      y: 140,
      text: '',
      w: 86,
      h: 50,
      normal_src: 'down_btn.png',
      press_src: 'down_btn_active.png',
      click_func: () => {
        set_min_func(-1)
      }
    })

    const sec_down_button = secGroup.createWidget(hmUI.widget.BUTTON, {
      x: 0,
      y: 140,
      text: '',
      w: 86,
      h: 50,
      normal_src: 'down_btn.png',
      press_src: 'down_btn_active.png',
      click_func: () => {
        set_sec_func(-1)
      }
    })

    hmUI.createWidget(hmUI.widget.BUTTON, {
      x: 0,
      y: 360,
      text: '',
      w: 192,
      h: 50,
      click_func: () => {
        let start_time = _get_time_sec()
        let total_sec = user_min * 60 + user_sec

        if (total_sec == 0) {
          return;
        }

        TmrStoreInt64(KEY_START_TIME_I64, start_time)
        TmrStoreInt(KEY_TIMER_STATE_I32, 1)
        TmrStoreInt64(KEY_TIME_TARGET_SEC_I64, start_time + total_sec)

        const alarm = hmApp.alarmNew({
          file: 'page/index',
          appid: 25727,
          delay: total_sec,
          param: 'TIMER_FINISHED'
        })

        TmrStoreInt(KEY_ALARM_ID_I32, alarm)

        // reload this page, but goto the timer controller page.
        hmApp.reloadPage({ url: 'page/index', param: '...' })
      },
      normal_src: 'play_btn.png',
      press_src: 'play_btn.png',
    })
  },

  _build_finish_page() {
    let _vibrate = getApp()._options.globalData._vibrate

    if (!getApp()._options.globalData._vibrate_ok) {
      getApp()._options.globalData._vibrate_ok = true
      _vibrate.stop()
      _vibrate.scene = 5
      _vibrate.start()
    } else {
      _vibrate.stop()
    }

    const text = hmUI.createWidget(hmUI.widget.TEXT, {
      x: 0,
      y: 120,
      w: 192,
      h: 46,
      color: 0xffffff,
      text_size: 40,
      align_h: hmUI.align.CENTER_H,
      align_v: hmUI.align.CENTER_V,
      text_style: hmUI.text_style.NONE,
      text: '计时结束'
    })

    hmUI.createWidget(hmUI.widget.BUTTON, {
      x: 0,
      y: 360,
      text: '',
      w: 192,
      h: 50,
      click_func: () => {
        TmrStoreInt(KEY_TIMER_STATE_I32, 0)
        hmApp.goBack()
      },
      normal_src: 'ok_btn.png',
      press_src: 'ok_btn.png',
    })
  },

  _build_pause_page() {
    let target_sec = TmrLoadInt64(KEY_TIME_TARGET_SEC_I64)
    let pause_time = TmrLoadInt64(KEY_START_TIME_I64)

    if (_check_undefined(target_sec)) {
      return Panic('target sec undefined')
    }

    if (_check_undefined(pause_time)) {
      return Panic('pause time undefined')
    }

    let [min, sec] = TmrTimeDeltaToMinAndSec(target_sec - pause_time)

    hmUI.createWidget(hmUI.widget.TEXT, {
      x: 0,
      y: 50,
      w: 192,
      h: 20,
      color: 0xffffff,
      text_size: 20,
      align_h: hmUI.align.CENTER_H,
      align_v: hmUI.align.CENTER_V,
      text_style: hmUI.text_style.NONE,
      text: '已暂停'
    })

    hmUI.createWidget(hmUI.widget.TEXT, {
      x: 10,
      y: 180,
      w: 86,
      h: 60,
      color: 0xffffff,
      text_size: 60,
      align_h: hmUI.align.CENTER_H,
      align_v: hmUI.align.CENTER_V,
      text_style: hmUI.text_style.NONE,
      text: String(min).padStart(2, '0')
    })

    hmUI.createWidget(hmUI.widget.TEXT, {
      x: 106,
      y: 180,
      w: 86,
      h: 60,
      color: 0xffffff,
      text_size: 60,
      align_h: hmUI.align.CENTER_H,
      align_v: hmUI.align.CENTER_V,
      text_style: hmUI.text_style.NONE,
      text: String(sec).padStart(2, '0')
    })

    hmUI.createWidget(hmUI.widget.TEXT, {
      x: 93,
      y: 180,
      w: 20,
      h: 50,
      color: 0xffffff,
      text_size: 50,
      align_h: hmUI.align.CENTER_H,
      align_v: hmUI.align.CENTER_V,
      text_style: hmUI.text_style.NONE,
      text: ':'
    })

    hmUI.createWidget(hmUI.widget.BUTTON, {
      x: 0,
      y: 300,
      text: '',
      w: 192,
      h: 50,
      click_func: () => {
        let cur_time = _get_time_sec()
        let delta = cur_time - pause_time
        target_sec += delta
        TmrStoreInt64(KEY_TIME_TARGET_SEC_I64, target_sec)

        TmrStoreInt(KEY_TIMER_STATE_I32, 1)

        const alarm = hmApp.alarmNew({
          file: 'page/index',
          appid: 25727,
          delay: target_sec - cur_time,
          param: 'TIMER_FINISHED'
        })

        TmrStoreInt(KEY_ALARM_ID_I32, alarm)

        hmApp.reloadPage({ url: 'page/index', param: '...' })
      },
      normal_src: 'play_btn.png',
      press_src: 'play_btn.png',
    })

    hmUI.createWidget(hmUI.widget.BUTTON, {
      x: 0,
      y: 360,
      text: '',
      w: 192,
      h: 50,
      click_func: () => {
        TmrStoreInt(KEY_TIMER_STATE_I32, 0)
        let alarm_id = TmrLoadInt(KEY_ALARM_ID_I32)
        if (_check_undefined(alarm_id)) {
          return Panic('Pause Page: alarm id = undefined')
        }
        hmApp.alarmCancel(alarm_id)
        hmApp.reloadPage({ url: 'page/index', param: '...' })
      },
      normal_src: 'stop_btn.png',
      press_src: 'stop_btn.png',
    })
  },

  _build_running_page() {
    let target_sec = TmrLoadInt64(KEY_TIME_TARGET_SEC_I64)

    if (_check_undefined(target_sec)) {
      return Panic('target sec undefined')
    }

    hmUI.createWidget(hmUI.widget.TEXT, {
      x: 0,
      y: 50,
      w: 192,
      h: 20,
      color: 0xffffff,
      text_size: 20,
      align_h: hmUI.align.CENTER_H,
      align_v: hmUI.align.CENTER_V,
      text_style: hmUI.text_style.NONE,
      text: '倒计时'
    })

    const min_text = hmUI.createWidget(hmUI.widget.TEXT, {
      x: 10,
      y: 180,
      w: 86,
      h: 60,
      color: 0xffffff,
      text_size: 60,
      align_h: hmUI.align.CENTER_H,
      align_v: hmUI.align.CENTER_V,
      text_style: hmUI.text_style.NONE,
      text: '00'
    })

    const sec_text = hmUI.createWidget(hmUI.widget.TEXT, {
      x: 106,
      y: 180,
      w: 86,
      h: 60,
      color: 0xffffff,
      text_size: 60,
      align_h: hmUI.align.CENTER_H,
      align_v: hmUI.align.CENTER_V,
      text_style: hmUI.text_style.NONE,
      text: '00'
    })

    hmUI.createWidget(hmUI.widget.TEXT, {
      x: 93,
      y: 180,
      w: 20,
      h: 50,
      color: 0xffffff,
      text_size: 50,
      align_h: hmUI.align.CENTER_H,
      align_v: hmUI.align.CENTER_V,
      text_style: hmUI.text_style.NONE,
      text: ':'
    })

    const _refresh_timer = timer.createTimer(
      10,
      10,
      function (_opt) {
        let [min, sec] = TmrGetMinAndSec(target_sec)
        if (min == -1) {
          timer.stopTimer(_refresh_timer)
          return
        }
        min_text.setProperty(hmUI.prop.TEXT, String(min).padStart(2, '0'))
        sec_text.setProperty(hmUI.prop.TEXT, String(sec).padStart(2, '0'))
      },
      {}
    )

    hmUI.createWidget(hmUI.widget.BUTTON, {
      x: 0,
      y: 300,
      text: '',
      w: 192,
      h: 50,
      click_func: () => {
        let alarm_id = TmrLoadInt(KEY_ALARM_ID_I32)
        if (_check_undefined(alarm_id)) {
          return Panic('PauseBtn: alarm id = undefined')
        }
        hmApp.alarmCancel(alarm_id)
        TmrStoreInt(KEY_ALARM_ID_I32, -1)

        timer.stopTimer(_refresh_timer)

        TmrStoreInt64(KEY_START_TIME_I64, _get_time_sec())
        TmrStoreInt(KEY_TIMER_STATE_I32, 2)
        hmApp.reloadPage({ url: 'page/index', param: '...' })
      },
      normal_src: 'pause_btn.png',
      press_src: 'pause_btn.png',
    })

    hmUI.createWidget(hmUI.widget.BUTTON, {
      x: 0,
      y: 360,
      text: '',
      w: 192,
      h: 50,
      click_func: () => {
        TmrStoreInt(KEY_TIMER_STATE_I32, 0)
        let alarm_id = TmrLoadInt(KEY_ALARM_ID_I32)
        if (_check_undefined(alarm_id)) {
          return Panic('Running Page: alarm id = undefined')
        }
        hmApp.alarmCancel(alarm_id)
        hmApp.reloadPage({ url: 'page/index', param: '...' })
      },
      normal_src: 'stop_btn.png',
      press_src: 'stop_btn.png',
    })
  },

  onInit(param) {
    if (param == 'TIMER_FINISHED') {
      TmrStoreInt(KEY_TIMER_STATE_I32, 3)
      getApp()._options.globalData._vibrate_ok = false

      TmrStoreInt(KEY_ALARM_ID_I32, -1)
    }
  },

  build() {
    if (DEBUG && !getApp()._options.globalData._debug_reset) {
      TmrStoreInt64(KEY_START_TIME_I64, 0)
      TmrStoreInt(KEY_TIMER_STATE_I32, 0)-
      TmrStoreInt64(KEY_TIME_TARGET_SEC_I64, 0)
      TmrStoreInt(KEY_ALARM_ID_I32, -1)
      getApp()._options.globalData._debug_reset = true
      hmUI.showToast({
        text: 'Debug Reset OK!'
      })
      hmApp.reloadPage({ url: 'page/index', param: '...' })
    }

    let state = TmrLoadInt(KEY_TIMER_STATE_I32)
    console.log('build page with state: ' + state)
    if (_check_undefined(state)) {
      state = 0
      TmrStoreInt(KEY_TIMER_STATE_I32, state)
      return this._build_init_page()
    }

    // page route
    switch (state) {
      case 0:
        return this._build_init_page()
      case 1:
        return this._build_running_page()
      case 2:
        return this._build_pause_page()
      case 3:
        return this._build_finish_page()
      default:
        return Panic('unexcepted state: ' + state)
    }
  },

  onDestroy() {
    getApp()._options.globalData._vibrate.stop()
  }
})
